using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using UnityEngine;
using System.Text;
using System.Linq;

namespace GenerativeAgents.Core
{
    /// <summary>
    /// 简化的语言模型实现
    /// 使用规则基础的方法模拟GPT等大语言模型的功能
    /// </summary>
    public class SimpleLanguageModel : MonoBehaviour, ILanguageModel
    {
        [Header("模型配置")]
        public float defaultTemperature = 0.7f;
        public int defaultMaxTokens = 150;
        public bool enableLogging = true;
        
        private Dictionary<string, string> responseTemplates;
        private Dictionary<string, int> importanceKeywords;
        private List<string> conversationStarters;
        private List<string> reflectionPrompts;
        private System.Random random;
        
        private void Awake()
        {
            InitializeLanguageModel();
        }
        
        private void InitializeLanguageModel()
        {
            random = new System.Random();
            responseTemplates = new Dictionary<string, string>();
            importanceKeywords = new Dictionary<string, int>();
            conversationStarters = new List<string>();
            reflectionPrompts = new List<string>();
            
            LoadTemplatesAndRules();
        }
        
        /// <summary>
        /// 异步生成响应
        /// </summary>
        public async Task<string> GenerateResponseAsync(string prompt, float temperature = 0.7f, int maxTokens = 150)
        {
            return await Task.Run(() => GenerateResponse(prompt, temperature, maxTokens));
        }
        
        /// <summary>
        /// 生成响应
        /// </summary>
        public string GenerateResponse(string prompt, float temperature = 0.7f, int maxTokens = 150)
        {
            if (string.IsNullOrEmpty(prompt))
                return "";
            
            var response = ProcessPrompt(prompt, temperature);
            
            // 限制响应长度
            if (response.Length > maxTokens * 4) // 粗略估算token长度
            {
                response = response.Substring(0, maxTokens * 4);
                // 确保在句号处截断
                var lastSentenceEnd = response.LastIndexOf('.');
                if (lastSentenceEnd > response.Length * 0.7f)
                {
                    response = response.Substring(0, lastSentenceEnd + 1);
                }
            }
            
            if (enableLogging)
            {
                Debug.Log($"LLM Prompt: {prompt}");
                Debug.Log($"LLM Response: {response}");
            }
            
            return response;
        }
        
        /// <summary>
        /// 异步评估重要性分数
        /// </summary>
        public async Task<int> ScoreImportanceAsync(string eventDescription)
        {
            return await Task.Run(() => ScoreImportance(eventDescription));
        }
        
        /// <summary>
        /// 评估事件重要性分数
        /// </summary>
        public int ScoreImportance(string eventDescription)
        {
            if (string.IsNullOrEmpty(eventDescription))
                return 1;
            
            int score = 3; // 基础分数
            var lowerDescription = eventDescription.ToLower();
            
            // 基于关键词评分
            foreach (var keyword in importanceKeywords)
            {
                if (lowerDescription.Contains(keyword.Key))
                {
                    score += keyword.Value;
                }
            }
            
            // 基于句法特征评分
            if (lowerDescription.Contains("!"))
                score += 1; // 感叹号增加重要性
            
            if (lowerDescription.Contains("?"))
                score += 1; // 问号增加重要性
            
            if (lowerDescription.Contains("very") || lowerDescription.Contains("extremely"))
                score += 1; // 强调词增加重要性
            
            // 检查情感词汇
            var emotionWords = new[] { "love", "hate", "angry", "excited", "sad", "happy", "worried", "afraid" };
            foreach (var emotion in emotionWords)
            {
                if (lowerDescription.Contains(emotion))
                {
                    score += 2;
                    break;
                }
            }
            
            // 检查社交互动
            var socialWords = new[] { "meet", "talk", "conversation", "friend", "enemy", "relationship" };
            foreach (var social in socialWords)
            {
                if (lowerDescription.Contains(social))
                {
                    score += 1;
                    break;
                }
            }
            
            // 确保分数在1-10范围内
            return Mathf.Clamp(score, 1, 10);
        }
        
        /// <summary>
        /// 异步提取关键词
        /// </summary>
        public async Task<List<string>> ExtractKeywordsAsync(string text, int maxKeywords = 5)
        {
            return await Task.Run(() => ExtractKeywords(text, maxKeywords));
        }
        
        /// <summary>
        /// 提取关键词
        /// </summary>
        public List<string> ExtractKeywords(string text, int maxKeywords = 5)
        {
            if (string.IsNullOrEmpty(text))
                return new List<string>();
            
            var words = PreprocessText(text);
            var keywordScores = new Dictionary<string, float>();
            
            // 计算词频
            var wordFreq = new Dictionary<string, int>();
            foreach (var word in words)
            {
                wordFreq[word] = wordFreq.GetValueOrDefault(word, 0) + 1;
            }
            
            // 计算关键词分数
            foreach (var word in wordFreq.Keys)
            {
                float score = wordFreq[word]; // 基础频率分数
                
                // 长度加成
                if (word.Length > 4)
                    score += 0.5f;
                
                // 重要词汇加成
                if (importanceKeywords.ContainsKey(word))
                    score += importanceKeywords[word] * 0.1f;
                
                // 词性加成（简化版）
                if (IsNoun(word))
                    score += 1f;
                else if (IsVerb(word))
                    score += 0.8f;
                else if (IsAdjective(word))
                    score += 0.6f;
                
                keywordScores[word] = score;
            }
            
            // 按分数排序并返回前N个
            return keywordScores
                .OrderByDescending(kv => kv.Value)
                .Take(maxKeywords)
                .Select(kv => kv.Key)
                .ToList();
        }
        
        /// <summary>
        /// 处理提示词并生成响应
        /// </summary>
        private string ProcessPrompt(string prompt, float temperature)
        {
            var lowerPrompt = prompt.ToLower();
            
            // 识别提示词类型并生成相应响应
            if (lowerPrompt.Contains("reflection") || lowerPrompt.Contains("reflect"))
            {
                return GenerateReflection(prompt, temperature);
            }
            else if (lowerPrompt.Contains("conversation") || lowerPrompt.Contains("chat"))
            {
                return GenerateConversationResponse(prompt, temperature);
            }
            else if (lowerPrompt.Contains("plan") || lowerPrompt.Contains("planning"))
            {
                return GeneratePlanningResponse(prompt, temperature);
            }
            else if (lowerPrompt.Contains("importance") || lowerPrompt.Contains("significant"))
            {
                return GenerateImportanceResponse(prompt, temperature);
            }
            else
            {
                return GenerateGeneralResponse(prompt, temperature);
            }
        }
        
        /// <summary>
        /// 生成反思响应
        /// </summary>
        private string GenerateReflection(string prompt, float temperature)
        {
            var reflectionTemplates = new[]
            {
                "Based on recent events, I think {insight}. This suggests that {conclusion}.",
                "Reflecting on what happened, it seems like {observation}. I should {action}.",
                "Looking back, I notice that {pattern}. This means {implication}.",
                "After thinking about it, I realize {realization}. Going forward, {plan}."
            };
            
            var template = reflectionTemplates[random.Next(reflectionTemplates.Length)];
            
            // 简化的模板填充
            var insight = GenerateInsight(prompt);
            var conclusion = GenerateConclusion(insight);
            
            return template
                .Replace("{insight}", insight)
                .Replace("{conclusion}", conclusion)
                .Replace("{observation}", insight)
                .Replace("{action}", GenerateAction())
                .Replace("{pattern}", insight)
                .Replace("{implication}", conclusion)
                .Replace("{realization}", insight)
                .Replace("{plan}", GenerateAction());
        }
        
        /// <summary>
        /// 生成对话响应
        /// </summary>
        private string GenerateConversationResponse(string prompt, float temperature)
        {
            var conversationTemplates = new[]
            {
                "I think {topic} is really interesting. {elaboration}",
                "About {topic}, I feel that {opinion}. What do you think?",
                "I remember {memory} about {topic}. {reflection}",
                "{topic} reminds me of {association}. {connection}"
            };
            
            var template = conversationTemplates[random.Next(conversationTemplates.Length)];
            var topic = ExtractMainTopic(prompt);
            
            return template
                .Replace("{topic}", topic)
                .Replace("{elaboration}", GenerateElaboration(topic))
                .Replace("{opinion}", GenerateOpinion(topic))
                .Replace("{memory}", GenerateMemoryReference())
                .Replace("{reflection}", GenerateReflectionFragment())
                .Replace("{association}", GenerateAssociation(topic))
                .Replace("{connection}", GenerateConnection());
        }
        
        /// <summary>
        /// 生成计划响应
        /// </summary>
        private string GeneratePlanningResponse(string prompt, float temperature)
        {
            var planningTemplates = new[]
            {
                "I should {action} at {time} in {location}. This will help me {goal}.",
                "My plan is to {action} because {reason}. I'll do this {when}.",
                "I want to {goal}, so I'll {action} and then {followup}.",
                "Given {context}, I think I should {action} to achieve {outcome}."
            };
            
            var template = planningTemplates[random.Next(planningTemplates.Length)];
            
            return template
                .Replace("{action}", GeneratePlanAction())
                .Replace("{time}", GenerateTimeReference())
                .Replace("{location}", GenerateLocationReference())
                .Replace("{goal}", GenerateGoal())
                .Replace("{reason}", GenerateReason())
                .Replace("{when}", GenerateTimeReference())
                .Replace("{followup}", GeneratePlanAction())
                .Replace("{context}", GenerateContextReference())
                .Replace("{outcome}", GenerateOutcome());
        }
        
        /// <summary>
        /// 生成一般响应
        /// </summary>
        private string GenerateGeneralResponse(string prompt, float temperature)
        {
            var generalTemplates = new[]
            {
                "I understand. {elaboration}",
                "That's interesting. {thought}",
                "I see. {response}",
                "Yes, {agreement}. {addition}"
            };
            
            var template = generalTemplates[random.Next(generalTemplates.Length)];
            
            return template
                .Replace("{elaboration}", "Let me think about this more.")
                .Replace("{thought}", "This makes me consider other possibilities.")
                .Replace("{response}", "I should keep this in mind.")
                .Replace("{agreement}", "I can relate to that")
                .Replace("{addition}", "There might be more to consider here.");
        }
        
        // 辅助方法
        private string GenerateInsight(string prompt)
        {
            var insights = new[]
            {
                "people's behaviors often reveal their true intentions",
                "patterns in daily routines can be quite telling",
                "social interactions are more complex than they appear",
                "timing and context matter a lot in relationships"
            };
            return insights[random.Next(insights.Length)];
        }
        
        private string GenerateConclusion(string insight)
        {
            var conclusions = new[]
            {
                "I should pay more attention to these details",
                "this could help me understand others better",
                "I need to be more observant in similar situations",
                "this pattern might repeat in the future"
            };
            return conclusions[random.Next(conclusions.Length)];
        }
        
        private string GenerateAction()
        {
            var actions = new[]
            {
                "be more observant",
                "ask more questions",
                "pay closer attention",
                "remember this for next time"
            };
            return actions[random.Next(actions.Length)];
        }
        
        private string ExtractMainTopic(string prompt)
        {
            // 简化的主题提取
            var words = PreprocessText(prompt);
            return words.FirstOrDefault() ?? "this";
        }
        
        private List<string> PreprocessText(string text)
        {
            var words = new List<string>();
            var cleanText = text.ToLower()
                .Replace(".", "")
                .Replace(",", "")
                .Replace("!", "")
                .Replace("?", "")
                .Replace("\"", "")
                .Replace("'", "");
            
            var tokens = cleanText.Split(new char[] { ' ', '\t', '\n' }, StringSplitOptions.RemoveEmptyEntries);
            var stopWords = new HashSet<string> { "the", "a", "an", "and", "or", "but", "in", "on", "at", "to", "for", "of", "with", "by", "is", "was", "are", "were", "be", "been", "have", "has", "had", "do", "does", "did", "will", "would", "could", "should" };
            
            foreach (var token in tokens)
            {
                if (token.Length > 1 && !stopWords.Contains(token))
                {
                    words.Add(token);
                }
            }
            
            return words;
        }
        
        private bool IsNoun(string word)
        {
            // 简化的名词识别
            var nounSuffixes = new[] { "tion", "sion", "ness", "ment", "er", "or", "ist" };
            return nounSuffixes.Any(suffix => word.EndsWith(suffix));
        }
        
        private bool IsVerb(string word)
        {
            // 简化的动词识别
            var verbSuffixes = new[] { "ing", "ed", "ate", "ize", "fy" };
            return verbSuffixes.Any(suffix => word.EndsWith(suffix));
        }
        
        private bool IsAdjective(string word)
        {
            // 简化的形容词识别
            var adjSuffixes = new[] { "ful", "less", "ous", "ive", "al", "ic", "ly" };
            return adjSuffixes.Any(suffix => word.EndsWith(suffix));
        }
        
        private void LoadTemplatesAndRules()
        {
            // 加载重要性关键词
            importanceKeywords = new Dictionary<string, int>
            {
                // 高重要性词汇
                { "death", 5 }, { "birth", 4 }, { "marriage", 4 }, { "divorce", 4 },
                { "promotion", 3 }, { "fired", 4 }, { "accident", 4 }, { "emergency", 4 },
                { "love", 3 }, { "hate", 3 }, { "fight", 3 }, { "argument", 2 },
                
                // 中等重要性词汇
                { "meeting", 2 }, { "party", 2 }, { "celebration", 2 }, { "vacation", 2 },
                { "sick", 2 }, { "tired", 1 }, { "hungry", 1 }, { "thirsty", 1 },
                { "work", 1 }, { "job", 2 }, { "school", 1 }, { "study", 1 },
                
                // 社交重要性词汇
                { "friend", 2 }, { "family", 3 }, { "relationship", 3 }, { "date", 2 },
                { "conversation", 1 }, { "talk", 1 }, { "discuss", 1 }, { "share", 1 }
            };
        }
        
        // 更多辅助方法
        private string GenerateElaboration(string topic) => "It's something I've been thinking about lately.";
        private string GenerateOpinion(string topic) => "it's quite fascinating";
        private string GenerateMemoryReference() => "something similar happening before";
        private string GenerateReflectionFragment() => "It makes me wonder about the connections.";
        private string GenerateAssociation(string topic) => "other related experiences";
        private string GenerateConnection() => "Everything seems interconnected somehow.";
        private string GeneratePlanAction() => "take some time to focus on this";
        private string GenerateTimeReference() => "later today";
        private string GenerateLocationReference() => "the appropriate place";
        private string GenerateGoal() => "understand this better";
        private string GenerateReason() => "it seems important";
        private string GenerateContextReference() => "everything that's been happening";
        private string GenerateOutcome() => "a better understanding";
        private string GenerateImportanceResponse(string prompt, float temperature) => $"This seems quite significant. I would rate its importance as {ScoreImportance(prompt)} out of 10.";
    }
}